<template>
  <div class="auth-container">
    <div class="auth-form">
      <h2>{{ isLogin ? $t('message.login') : $t('message.register') }}</h2>
      
      <!-- Registration Form -->
      <form v-if="!isLogin" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="reg-username">{{ $t('message.username') }}:</label>
          <input 
            type="text" 
            id="reg-username" 
            v-model="registrationForm.username" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="reg-email">{{ $t('message.email') }}:</label>
          <input 
            type="email" 
            id="reg-email" 
            v-model="registrationForm.email" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="reg-password">{{ $t('message.password') }}:</label>
          <input 
            type="password" 
            id="reg-password" 
            v-model="registrationForm.password" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="reg-role">{{ $t('message.role') }}:</label>
          <select id="reg-role" v-model="registrationForm.role" required>
            <option value="PARENT">{{ $t('message.parent') }}</option>
            <option value="TEACHER">{{ $t('message.teacher') }}</option>
            <option value="ASSISTANT">{{ $t('message.assistant') }}</option>
            <option value="ADMIN">{{ $t('message.admin') }}</option>
          </select>
        </div>
        
        <button type="submit" :disabled="loading" class="btn btn-primary">
          <span v-if="loading">{{ $t('message.registering') }}</span>
          <span v-else>{{ $t('message.registeringText') }}</span>
        </button>
      </form>
      
      <!-- Login Form -->
      <form v-else @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="login-username">{{ $t('message.usernameOrEmail') }}:</label>
          <input 
            type="text" 
            id="login-username" 
            v-model="loginForm.username" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="login-password">{{ $t('message.password') }}:</label>
          <input 
            type="password" 
            id="login-password" 
            v-model="loginForm.password" 
            required
          />
        </div>
        
        <button type="submit" :disabled="loading" class="btn btn-primary">
          <span v-if="loading">{{ $t('message.loggingIn') }}</span>
          <span v-else>{{ $t('message.loggingInText') }}</span>
        </button>
      </form>
      
      <div class="auth-switch">
        <p>
          {{ isLogin ? $t('message.dontHaveAccount') : $t('message.alreadyHaveAccount') }}
          <a href="#" @click.prevent="toggleForm">
            {{ isLogin ? $t('message.registerHere') : $t('message.loginHere') }}
          </a>
        </p>
      </div>
      
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'AuthComponent',
  setup() {
    const isLogin = ref(true)
    const loading = ref(false)
    const error = ref('')
    
    const registrationForm = ref({
      username: '',
      email: '',
      password: '',
      role: 'PARENT' // default role
    })
    
    const loginForm = ref({
      username: '',
      password: ''
    })
    
    const router = useRouter()
    const authStore = useAuthStore()
    
    const toggleForm = () => {
      isLogin.value = !isLogin.value
      error.value = ''
    }
    
    const handleRegister = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const response = await fetch('/api/auth/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(registrationForm.value)
        })
        
        const data = await response.json()
        
        if (!response.ok) {
          throw new Error(data.error || 'Registration failed')
        }
        
        // On successful registration, go to login
        isLogin.value = true
        registrationForm.value = {
          username: '',
          email: '',
          password: '',
          role: 'PARENT'
        }
      } catch (err) {
        error.value = err.message
      } finally {
        loading.value = false
      }
    }
    
    const handleLogin = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const response = await fetch('/api/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(loginForm.value)
        })
        
        const data = await response.json()
        
        if (!response.ok) {
          throw new Error(data.error || 'Login failed')
        }
        
        // Store token and user info
        const actualUser = data.user.user || data.user
        localStorage.setItem('token', data.token)
        authStore.setToken(data.token)
        authStore.setUser(actualUser)
        
        // Redirect based on user role
        if (actualUser.roleId === 'ADMIN') {
          router.push('/admin')
        } else {
          router.push('/')
        }
      } catch (err) {
        error.value = err.message
      } finally {
        loading.value = false
      }
    }
    
    return {
      isLogin,
      loading,
      error,
      registrationForm,
      loginForm,
      toggleForm,
      handleRegister,
      handleLogin
    }
  }
}
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 20px;
}

.auth-form {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  background-color: white;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.btn {
  width: 100%;
  padding: 0.75rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.auth-switch {
  margin-top: 1.5rem;
  text-align: center;
}

.auth-switch p {
  margin: 0;
  font-size: 0.9rem;
  color: #666;
}

.auth-switch a {
  color: #007bff;
  text-decoration: none;
}

.error-message {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  text-align: center;
}
</style>